package com.web.portal.config;

import com.web.portal.config.vo.JwtToken;
import com.web.portal.config.vo.LoginUserVo;
import com.web.portal.pojo.PortalUser;
import com.web.portal.services.UserService;
import com.web.portal.utils.ClaimsUtils;
import com.web.portal.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //打印一个提示
        System.out.println("执行了授权方法");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        PortalUser currentUser = userService.checkSobUser();
//         获取用户
        if (currentUser.getRoles().equals("0") || currentUser.getRoles().equals("1")) {
            // 获取当前用户的权限
            info.addStringPermission("admin");
        }

        return info;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = (String) authenticationToken.getCredentials();
        if (token == null) {
            log.info("————————身份认证失败——————————");
            throw new AuthenticationException("token为空!");
        }
        Claims claims = JwtUtil.parseJWT(token);
        PortalUser portalUser = ClaimsUtils.claims2Claims(claims);
        LoginUserVo vo = new LoginUserVo();
        BeanUtils.copyProperties(portalUser,vo);
        vo.setToken(token);
        return new SimpleAuthenticationInfo(vo, token, getName());
    }

    // 在登录的时候判断
    /**
     * 限定这个realm只能处理jwtToken(不加会报错)
     *
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }


}
